/**
 * 
 */
package com.uit.project.bustrip.bo;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.uit.project.bustrip.appconfig.AppsConfig;
import com.uit.project.bustrip.bointerface.UserBO;
import com.uit.project.bustrip.daointerface.UserDao;
import com.uit.project.bustrip.entity.User;
import com.uit.project.bustrip.ultil.JSONUltil;
import com.uit.project.bustrip.valueobject.LoginInfo;

/**
 * @author Nguyen
 *
 */
public class UserBOImpl extends BaseBOImpl<User, Integer> implements UserBO{
	public UserBOImpl(){
		super();
	}
	public UserBOImpl(Context context){
		super(context);
	}
	@Override
	public User getInstance() {
		List<User> users = ((UserDao)this.getDao()).findAll();
		if(users.size() > 0)
			return users.get(0);
		return null;
	}
	@Override
	public LoginInfo loginAsync(String phone, String pass) {
		String url = AppsConfig.getServiceURL();
		JSONObject result = JSONUltil.getJSONObjectFromURL(url);
		if(result != null){
			LoginInfo loginInfo = null;
			try {
				JSONObject loginResult = result.getJSONObject(AppsConfig.JSON_OBJECT);
				if(loginResult != null){
					loginInfo = getLoginInfo(loginResult);
					return loginInfo;
				}	
				else{
					return null;
				}
			} catch (JSONException e) {
				return null;
			}
		}
		return null;
	}
	public LoginInfo getLoginInfo(JSONObject json){
		LoginInfo info = new LoginInfo();
		try {
			info.setResult(json.getString(AppsConfig.JSON_RESULT));
//			info.setData(json.getString(AppsConfig.JSON_RESULT));
			info.setMessage(json.getString(AppsConfig.JSON_MESSAGE));
		} catch (Exception e) {
			Log.e("UserBOImpl - getLoginInfo",e.getMessage());
			return null;
		}
		return info;
	}
}

